package com.vito.careworker.controller;

import android.app.Activity;
import android.os.Build;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.vito.base.action.Action;
import com.vito.base.action.ActionParser;
import com.vito.base.jsonbean.VitoJsonTemplateBean;
import com.vito.base.ui.widget.AllShowGridView;
import com.vito.base.ui.widget.BadgeView;
import com.vito.base.utils.ToastShow;
import com.vito.base.utils.network.httplibslc.RequestVo;
import com.vito.base.utils.network.jsonpaser.JsonLoader;
import com.vito.careworker.R;
import com.vito.careworker.adapter.QuickEntriesAdapter;
import com.vito.careworker.data.FunItem;
import com.vito.careworker.data.GroupFuns;
import com.vito.careworker.helpers.HomeMoreFunHelper;
import com.vito.careworker.helpers.MoreHelper;
import com.vito.careworker.utils.Comments;

import org.codehaus.jackson.type.TypeReference;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by lenovo on 2016/6/29.
 */
public class QuickEntiyCtrller extends BaseCtrller implements MoreHelper.MoreHelperCallBack {

    AllShowGridView mGridView;
    TextView mGroupNameView;
    JsonLoader mJsonLoader;
    QuickEntriesAdapter mGridadapter;
    String mTag;

    public QuickEntiyCtrller(Activity activity, ViewGroup rootView, String in_name) {
        super(activity, rootView);
        RelativeLayout ll = (RelativeLayout) View.inflate(activity, R.layout.listview_quickentiy, null);
        rootView.addView(ll);
        mGridView = (AllShowGridView) ll.findViewById(R.id.quick_lv);
        mGroupNameView = (TextView) ll.findViewById(R.id.tv_groupname);
//        mGroupNameView.setText(in_name);
        mTag = in_name;
//        if (mTag.equals("work_second"))
//            ViewFindUtils.find(ll, R.id.line_base).setVisibility(View.GONE);
//        else
//            ViewFindUtils.find(ll, R.id.line_base).setVisibility(View.VISIBLE);
        mJsonLoader = new JsonLoader(mContext, this);
//        JsonLoader loader = new JsonLoader(mContext,mHandler,1);
//        loader.load(FileUtils.getDataPathDefaultAssets(mContext ,Comments.QuckEntity_DATA_PATH), GroupAppData.class);
        mGridadapter = new QuickEntriesAdapter(mContext, R.layout.view_quickentry_item);
        mGridadapter.setmLoadLocalImg(true);
        mGridView.setAdapter(mGridadapter);
        MoreHelper.getInstance().getData(this);
    }

    void initViews(GroupFuns re_data) {
        if (re_data == null || re_data.getTabs().size() <= 0)
            return;

//        final List<FunItem> data_list = re_data.getTabs();
        if (re_data.getTabs() == null || re_data.getTabs().size() == 0)
            return;
        mGroupNameView.setText(re_data.getTab_name());

        int listsize = re_data.getTabs().size();
        if (listsize % mGridView.getNumColumns() != 0) {
            for (int i = 0; i < (mGridView.getNumColumns() - listsize % mGridView.getNumColumns()); i++) {
                FunItem temp = new FunItem();
                re_data.getTabs().add(temp);
            }
        }

        mGridadapter.setData(re_data.getTabs());
        mGridadapter.notifyDataSetChanged();

        mGridView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                getNoReadNum();
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                    mGridView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                } else {
                    mGridView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                }
            }
        });
        mGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (mGridadapter.getItem(position).getModuleurl() == null)
                    return;

                Action localac = HomeMoreFunHelper.getInstance().getActionByTag(
                        mGridadapter.getItem(position).getModuleurl());
                if (localac == null) {
                    String str = mGridadapter.getItem(position).getModuleurl();
                    if (str.startsWith("/")) {
                        localac.setmActionType("Fragment");
                        localac.setContentName("rootfragcontent");
                        localac.setFragmentName("com.vito.fragments.URLFragment");

                        HashMap map = new HashMap<>();
                        map.put("BaseUrl", mGridadapter.getItem(position).getModuleurl());
                        localac.setmParameters(map);
                    } else {
//                        BaseFragment fg = FragmentFactory.getInstance().createFragment("com.vito.cloudoa.fragments","CloudDiskFragment");
//                        changeMainFragment(fg,true);
                        ToastShow.toastShow(R.string.empty_fun, ToastShow.LENGTH_SHORT);
                        return;
                    }
                } else {
                    ActionParser.getInstance().parseAction((Activity) mContext, localac, true);
                }
            }
        });
    }

    @Override
    public void onJsonDataGetSuccess(Object re_data, int reqcode) {
        switch (reqcode) {
            case 1:
//                initViews((JsonRootBean<MoreBean<Subs>>) re_data);
//                initView((VitoJsonTemplateBean<MoreBean<Subs>>)re_data);
                break;
            case 2:
                showBadge(re_data);
                break;
            default:
                break;
        }
    }

    @Override
    public void onJsonDataGetFailed(int re_code, String re_info, int reqcode) {

    }

    public void onResume() {
        getNoReadNum();
    }

    private void showBadge(Object re_data) {
        VitoJsonTemplateBean templateBean = (VitoJsonTemplateBean) re_data;
        if (templateBean.getCode() != 0) {
            return;
        }
//        HashMap map = (HashMap) templateBean.getData();
//        String sys_num = (String) map.get("systemNoReadNum");
        showBadge(1, (Integer) templateBean.getData());

//        String com_num = (String) map.get("communityNoReadNum");
//        showBadge(1, com_num);

    }

    private void showBadge(int typeid, int str_num) {
        String type = Comments.mBadgeTypes[typeid];
        for (int i = 0; i < mGridadapter.getCount(); i++) {
            if (mGridadapter.getItem(i).getModuleurl() == null)
                continue;

            Action localac = HomeMoreFunHelper.getInstance().getActionByTag(
                    mGridadapter.getItem(i).getModuleurl());
            if (localac != null && localac.getTag() != null && localac.getTag().get("noticeType") != null
                    && localac.getTag().get("noticeType").equals(type)) {
                if (mGridView == null || mGridView.getChildAt(i) == null)
                    return;
                FrameLayout fl = (FrameLayout) mGridView.getChildAt(i).findViewById(R.id.fl_root);
                for (int ii = 0; ii < fl.getChildCount(); ii++) {
                    if (fl.getChildAt(ii) instanceof BadgeView) {
                        fl.removeView(fl.getChildAt(ii));
                        break;
                    }
                }
                BadgeView badgeView = null;/* new BadgeView(mContext, ll);*/
                if (badgeView == null) {
                    badgeView = new BadgeView(mContext);
                    fl.addView(badgeView);
                }

                badgeView.setBadgePosition(BadgeView.POSITION_TOP_RIGHT);
//                badgeView.setBackgroundResource(R.drawable.circle_red);
                badgeView.setBadgeMargin(8, 2);
                badgeView.setText(" ");
                badgeView.setTextSize(9);
                if (str_num != 0) {
                    badgeView.show();
                } else {
                    badgeView.hide();
                }
                return;
            }
        }
    }

    private void getNoReadNum() {
        RequestVo rv = new RequestVo();
        rv.requestUrl = Comments.NOTICECOUNT_PATH;

        rv.requestDataMap = new HashMap<>();
        rv.requestDataMap.put("read", "false");
        mJsonLoader.load(rv, null,
                new TypeReference<VitoJsonTemplateBean<Integer>>() {
                }, JsonLoader.MethodType.MethodType_Post, 2);
    }

    @Override
    public void MoretOk(Map<String, GroupFuns> re_data) {
        if (re_data == null || re_data.size() == 0 || re_data.get(mTag) == null)
            return;

        initViews(re_data.get(mTag));
    }

    @Override
    public void MoreFail() {

    }
}
